package com.easy.interceptor;

//拦截器:登录拦截器

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.easy.util.Result;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的token
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        //判断token是否合法
        if (token == null ||!TokenUtil.verify(token)){
            Result result = new Result(401,"认证异常", null);
            //hutool
            String json = JSONUtil.toJsonStr( result);
            //fastjson
            JSON.toJSONString( result);
            //返回结果
            response.getWriter().print(json);
            return false;
        }
        //放行
        return true;

    }

}
